$(function() {
	var saveData = {};
	var saveList = [];
	var monitor_CurveId = localStorage.getItem('monitor_CurveId');
	console.log(monitor_CurveId)
	debugger;
	var _dataCurve = {
		init: function() {

		},
		bindEvent: function() {
			getMenu('my_menu_list', 'my_menu', MONITOR_URL + '/monitorCurve/getCurveTree');
			getSaveBox($('.icon-fenxiang'));
			hideBox($('#btnCancel'));
			lastMonthCompare(); //环比
			lastYearCompare(); //同比
			getRefresh($('.icon-shuaxin')); //刷新
		}
	}
	_dataCurve.init();
	_dataCurve.bindEvent();

	setTimeout(function() {
		$('.textTip').text('暂无数据!');
	}, 500)

	function getMenu(list, listBox, url) {
		$.ajax({
			type: "get",
			url: url,
			dataType: "json",
			async: true,
			success: function(data) {
				console.log('左侧树形', data)
				debugger;
				var listItems = data.data;
				var listData = {
					list: listItems
				};
				var html = template(list, listData);
				document.getElementById(listBox).innerHTML = html;
				getDrag();
				getZtreeMenu();
			}
		});
	}

	function getRefresh(obj) {
		obj.on('click', function() {
			$('#container').remove();
			$('.textTip').show();
			saveData.value = [];
			saveList = [];
			$('.echarts').append('<div id="container" style="height: 500px;"></div>');
		});
	}

	function getSaveBox(obj) {
		obj.on('click', function() {
			$('.save_box').toggle();
		});
	}

	function hideBox(obj) {
		obj.on('click', function() {
			$('.save_box').hide();
		});
	}

	function getZtreeMenu() {
		$('dt').on('click', function() {
			$(this).closest('dl').find('dd').toggle('fast')
		})
	}

	function lastMonthCompare() {
		$('.contrast_lastmonth_compare').on('change', function() {
			if($(this).prop('checked') && !$('.contrast_lastyear_compare').prop('checked')) {
				if(saveData.value && saveData.value.length > 1) {
					layer.msg('只能选择一个进行同比');
					$(this).prop('checked', false);
				} else if(saveData.value && saveData.value.length == 1) {
					saveData.type = 1;
					drawEcharts(saveData, MONITOR_URL + "/monitorCurve/getCurvesByMom");
				} else {
					layer.msg('请优先选择一个点');
					$(this).prop('checked', false);
				}
			} else if($(this).prop('checked') && !$('.contrast_lastyear_compare').prop('checked')) {
				layer.msg('请先取消环比');
			} else {
				delete saveData.type;
				drawEcharts(saveData, MONITOR_URL + "/monitorCurve/getCurves");
			}
		})
	}

	function lastYearCompare() {
		$('.contrast_lastyear_compare').on('change', function() {
			if($(this).prop('checked') && !$('.contrast_lastmonth_compare').prop('checked')) {
				if(saveData.value && saveData.value.length > 1) {
					layer.msg('只能选择一个环比');
					$(this).prop('checked', false);
				} else if(saveData.value && saveData.value.length == 1) {
					saveData.type = 2;
					drawEcharts(saveData, MONITOR_URL + "/monitorCurve/getCurvesByMom");
				} else {
					layer.msg('请优先选择一个点');
					$(this).prop('checked', false);
				}
			} else if($(this).prop('checked') && !$('.contrast_lastmonth_compare').prop('checked')) {
				layer.msg('请先取消同比');
			} else {
				delete saveData.type;
				drawEcharts(saveData, MONITOR_URL + "/monitorCurve/getCurves");
			}
		})
	}

	function drawEcharts(data, url) {
		var dom = document.getElementById("container");
		var myChart = echarts.init(dom);
		var app = {};
		option = null;
		console.log('data', data)
		$.ajax({
			type: "post",
			contentType: "application/json;charset=utf-8",
			url: url,
			data: JSON.stringify(data),
			dataType: "json",
			async: true,
			success: function(res) {
				console.log('res', res)
				var _dataList = res.data;
				if(_dataList == null) {
					$('.textTip').show();
				} else if(_dataList.length > 0) {

					$('.textTip').hide();

					var xAxisArrData = [];
					var yAxisArrData = [];
					var yAxisArr = [];
					var gridArr = [];
					var titleArr = [];
					var _length = _dataList.length;
					for(var i = 0; i < _dataList.length; i++) {
						if(_dataList[i].datalist.length == 0) {
							$('.textTip').show();
						} else {
							var xAxisObj = {};
							var yAxisObj = {};
							//						var title = '';
							var Times = new Date(_dataList[i].datalist[0].datadt);
							var _unit = _dataList[i].unit;
							var _year = Times.getFullYear();
							var _month = Times.getMonth() + 1;
							var _date = Times.getDate();
							var _hour = Times.getHours() < 10 ? '0' + Times.getHours() : Times.getHours();
							var _min = Times.getMinutes() < 10 ? '0' + Times.getMinutes() : Times.getMinutes();
							var _sec = Times.getSeconds() < 10 ? '0' + Times.getSeconds() : Times.getSeconds();;
							var Time = _year + '-' + _month + '-' + _date + ' ' + _hour + ":" + _min + ":" + _sec;
							var xdataArr = [];
							if(i == _dataList.length - 1) {
								xdataArr.push(Time)
								xAxisArrData.push({
									data: xdataArr,
									show: true,
									name: '时间',
									type: 'category',
									gridIndex: i
								})
							} else {
								xdataArr.push(Time)
								xAxisArrData.push({
									data: xdataArr,
									show: false,
									type: 'category',
									gridIndex: i
								})
							}
							var ydataArr = [];
							ydataArr.push(_dataList[i].datalist[0].value)
							yAxisArrData.push({
								type: 'line',
								showSymbol: false,
								data: ydataArr,
								xAxisIndex: i,
								yAxisIndex: i,
								label: {
									formatter: function(params) {
										return 111111
										console.log(params)
									}
								}
							})
							yAxisArr.push({
								splitLine: {
									show: false
								},
								name: _unit,
								gridIndex: i
							})
							if(i == 0) {
								gridArr.push({
									gridIndex: i,
									top: 10 + (100 / _length) * i + '%',
									bottom: ((100 / _length) * [_length - i - 1]) + 10 + '%'
								})
								titleArr.push({
									left: 'left',
									text: _dataList[i].shortname,
									top: (100 / _length) * i + '%',
									textStyle: {
										color: "#333",
										fontWeight: 500,
										fontSize: 12
									}
								})
							} else {
								gridArr.push({
									gridIndex: i,
									top: (100 / _length) * i + '%',
									bottom: ((100 / _length) * [_length - i - 1]) + 10 + '%'
								})
								titleArr.push({
									left: 'left',
									text: _dataList[i].shortname,
									top: -10 + (100 / _length) * i + '%',
									textStyle: {
										color: "#333",
										fontWeight: 500,
										fontSize: 12
									}
								})
							}
						}
					}
					option = {
						tooltip: {
							trigger: 'axis'
						},
						axisPointer: {
							link: {
								xAxisIndex: 'all'
							},
							label: {
								backgroundColor: '#777'
							}
						},

						//					title: [{
						//				        left: 'center',
						//				        text: 'Gradie'
						//				    }, {
						//				        top: '55%',
						//				        left: 'center',
						//				        text: 'Gradient along the x axis'
						//				    }],

						title: titleArr,
						xAxis: xAxisArrData,
						yAxis: yAxisArr,
						grid: gridArr,
						series: yAxisArrData
					};
					if(option && typeof option === "object") {
						myChart.setOption(option, true);
					}
				}
			},
			error: function(error) {

			}
		});

		//data = [["2000-06-05",116],["2000-06-06",129],["2000-06-07",135],["2000-06-08",86],["2000-06-09",73],["2000-06-10",85],["2000-06-11",73],["2000-06-12",68],["2000-06-13",92],["2000-06-14",130],["2000-06-15",245],["2000-06-16",139],["2000-06-17",115],["2000-06-18",111],["2000-06-19",309],["2000-06-20",206],["2000-06-21",137],["2000-06-22",128],["2000-06-23",85],["2000-06-24",94],["2000-06-25",71],["2000-06-26",106],["2000-06-27",84],["2000-06-28",93],["2000-06-29",85],["2000-06-30",73],["2000-07-01",83],["2000-07-02",125],["2000-07-03",107],["2000-07-04",82],["2000-07-05",44],["2000-07-06",72],["2000-07-07",106],["2000-07-08",107],["2000-07-09",66],["2000-07-10",91],["2000-07-11",92],["2000-07-12",113],["2000-07-13",107],["2000-07-14",131],["2000-07-15",111],["2000-07-16",64],["2000-07-17",69],["2000-07-18",88],["2000-07-19",77],["2000-07-20",83],["2000-07-21",111],["2000-07-22",57],["2000-07-23",55],["2000-07-24",60]];
		//
		//var dateList = data.map(function (item) {
		//  return item[0];
		//});
		//var valueList = data.map(function (item) {
		//  return item[1];
		//});

	}

	var nowTime = new Date();
	var _year, _month, _date, _yestdate, _hour, _min, _sec, Time,
		_lastYear, _lastMonth, _lastTime;

	_year = nowTime.getFullYear();
	_month = nowTime.getMonth() + 1;
	_lastMonth = nowTime.getMonth;
	_date = nowTime.getDate();
	_yestdate = nowTime.getDate() - 1;

	_hour = nowTime.getHours() < 10 ? '0' + nowTime.getHours() : nowTime.getHours();
	_min = nowTime.getMinutes() < 10 ? '0' + nowTime.getMinutes() : nowTime.getMinutes();
	_sec = nowTime.getSeconds() < 10 ? '0' + nowTime.getSeconds() : nowTime.getSeconds();;
	Time = _year + '-' + _month + '-' + _date + ' ' + _hour + ":" + _min + ":" + _sec;

	if(nowTime.getMonth() == 0) { //如果当前月份为1月，就获取上一年的12月份
		_lastYear = nowTime.getFullYear() - 1;
		_lastMonth = 12;
	} else {
		_lastYear = nowTime.getFullYear();
		_lastMonth = nowTime.getMonth();
	}

	_lastTime = _lastYear + '-' + _lastMonth + '-' + _date + ' ' + _hour + ":" + _min + ":" + _sec;
	$('#startDate').val(_lastTime);
	$('#endDate').val(Time);

	function getDrag() {
		$('.grad_menu_ztree>dd').draggable({
			revert: true,
			proxy: 'clone',
			onStartDrag: function() {
				$(this).draggable('options').cursor = 'pointer';
				$(this).draggable('proxy').css('z-index', 99999);
			},
			onStopDrag: function() {
				$(this).draggable('options').cursor = 'move';

				var id = $(this).attr('data-id');
				var instrumentId = $(this).attr('data-instrid');

				console.log(id, instrumentId)

				saveData.value = [];
				saveData.sTime = $('#startDate').val();
				saveData.eTime = $('#endDate').val();
				saveList.push({
					instrumentId: instrumentId,
					quotaId: id
				})
				var hash = {};
				var result = [];
				for(var i = 0, len = saveList.length; i < len; i++) {
					if(!hash[saveList[i].instrumentId + saveList[i].quotaId]) {
						result.push(saveList[i]);
						hash[saveList[i].instrumentId + saveList[i].quotaId] = true;
					}
				}
				saveData.value = result;
				var conTextBox = [];
				$('#time input').each(function() {
					var conText = $(this).val();
					conTextBox.push(conText)
					if(!conText) {
						$(this).addClass('active');
						$(this).next().show().delay(3000).hide(0);
						return false;
					} else {
						$(this).removeClass('active');
					}
					return conText;
				})
				if(conTextBox.length == 2) {
					drawEcharts(saveData, MONITOR_URL + "/monitorCurve/getCurves");
				}
				getSaveData(result, $('#btnSubmit'))
			}
		});
	}

	function getSaveData(result, obj) {
		obj.on('click', function() {
			var _echartData = {};
			_echartData.fld = '';
			_echartData.id = '';
			_echartData.name = $('#dataCurve_name').val();
			_echartData.value = result;
			console.log(_echartData)
			debugger;
			$.ajax({
				type: "post",
				contentType: "application/json;charset=utf-8",
				url: MONITOR_URL + "/monitorCurve/saveOrUpdate",
				data: JSON.stringify(_echartData),
				dataType: "json",
				async: true,
				success: function(res) {
					layer.msg('保存成功');
					$('.save_box').hide();
					setTimeout(function() {
						$('#container').remove();
						$('.textTip').show();
						saveData.value = [];
						$('.echarts').append('<div id="container" style="height: 500px;"></div>');
					}, 3000)
				},
				error: function(error) {
					console.log(error)
				}
			})
		})
	}

	//$('.echarts').droppable({
	//	onDragEnter:function(e,source){
	//		$(source).draggable('options').cursor='auto';
	//	},
	//	onDragLeave:function(e,source){
	//		$(source).draggable('options').cursor='not-allowed';
	//	},
	//	onDrop:function(e,source){
	//		console.log(e);
	//		console.log(source)
	//		var name = $(source).find('span').html();
	//		var price = $(source).find('p:eq(1)').html();
	//		console.log(name);
	//		console.log(price);
	////		addProduct(name, parseFloat(price.split('$')[1]));
	//	}
	//});
})